package study.springcloud.config.nacos.support.utils;

import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.aop.framework.AopProxy;
import org.springframework.aop.support.AopUtils;

import java.lang.reflect.Field;

public final class AopTargetUtils {

    private AopTargetUtils() {
    }

    /**
     * 获取目标对象
     *
     * @param proxy 代理对象
     * @return Object
     */
    public static Object getTarget(Object proxy) {
        //不是代理对象
        if (!AopUtils.isAopProxy(proxy)) {
            return proxy;
        }
        Object target ;
        try {
            if (AopUtils.isJdkDynamicProxy(proxy)) {
                //jdk proxy
                target = getJdkDynamicProxyTarget(proxy);
            } else  {
                //cglib proxy
                target = getCglibProxyTarget(proxy);
            }
        } catch (Exception ex) {
            throw new RuntimeException("", ex);
        }
        return target;
    }

    private static Object getCglibProxyTarget(Object proxy) throws Exception {
        //
        Field f = proxy.getClass()
                .getDeclaredField("CGLIB$CALLBACK_0");
        f.setAccessible(true);
        Object dynamicAdvisedInterceptor = f.get(proxy);
        //
        Field advised = dynamicAdvisedInterceptor.getClass()
                .getDeclaredField("advised");
        advised.setAccessible(true);
        Object target = ((AdvisedSupport) advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();
        return target;
    }

    private static Object getJdkDynamicProxyTarget(Object proxy) throws Exception {
        //
        Field h = proxy.getClass().getSuperclass()
                .getDeclaredField("h");
        h.setAccessible(true);
        AopProxy aopProxy = (AopProxy) h.get(proxy);
        //
        Field advised = aopProxy.getClass()
                .getDeclaredField("advised");
        advised.setAccessible(true);
        //
        Object target = ((AdvisedSupport) advised.get(aopProxy))
                .getTargetSource()
                .getTarget();
        return target;
    }
}
